import { bindable, bindingMode, containerless } from 'aurelia-framework';

@containerless
export class EmDropdown {

    @bindable name = _.uniqueId('em-dropdown-');
    @bindable text = '';
    @bindable label = 'label';
    @bindable value = 'value';
    @bindable({ defaultBindingMode: bindingMode.twoWay }) selected;
    @bindable items = [];
    @bindable classes = 'selection';
    @bindable onchange;
    @bindable allowAdditions = false;

    selectedChanged(news, old) {

        if (news) {
            _.defer(() => {
                $(this.dropdown).dropdown('set selected', news);
                // console.log('selectedChanged: ' + news);
            });
        } else {
            _.defer(() => {
                $(this.dropdown).dropdown('clear');
            });
        }

    }

    itemsChanged(news, old) {
        if (_.isEmpty(news)) {
            $(this.dropdown).dropdown('clear');
            this.selected = null;
        }
    }

    /**
     * 当视图被附加到DOM中时被调用
     */
    attached() {
        $(this.dropdown).dropdown({
            allowAdditions: this.allowAdditions ? this.allowAdditions : false,
        });
    }

    initDropdownHandler(last) {

        if (last) {
            _.defer(() => {
                $(this.dropdown).dropdown({
                    allowAdditions: this.allowAdditions == 1 ? true : false,
                    onChange: (value, text, $choice) => {
                        // toastr.info(value + ' | ' + text);
                        this.selected = value;
                        this.onchange && this.onchange(value);
                    }
                }).dropdown('set selected', this.selected);
                // console.log('initDropdownHandler: ' + this.selected);
            });
        }
    }
}
